package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.dao.jdbc.StudentEvaluationScoreJdbc;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.mapper.StudentEvaluationScoreMapper;
import com.wuseguang.springcloud.dao.repository.*;
import com.wuseguang.springcloud.entity.*;
import com.wuseguang.springcloud.service.StudentEvaluationScoreService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 学生评价分数表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-02-02
 */
@Service
public class StudentEvaluationScoreServiceImpl implements StudentEvaluationScoreService {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StudentEvaluationScoreRecordRepository studentEvaluationScoreRecordRepository;
    @Autowired
    private StudentEvaluationScoreJdbc studentEvaluationScoreJdbc;
    @Autowired
    private StudentEvaluationScoreRepository studentEvaluationScoreRepository;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private WXJdbc wXJdbc;
    @Autowired
    private StudentExchangeDetailsRepository studentExchangeDetailsRepository;
    @Autowired
    private TeacherRatingLimitRepository teacherRatingLimitRepository;
    @Autowired
    private RatingLimitsCustomizedRepository ratingLimitsCustomizedRepository;


    @Override
    public Result findClassEvaluationScore(Integer classId, String teacherId, String termId) {

        logger.info("查询没个班级的学生评分信息");
        //查询教师的显示规则并且返回规则id
        String id = studentEvaluationScoreJdbc.findTeacherRule(teacherId);

        Map<String, Object> returnMap = new HashMap<>();

        //查询班级程序SQL
        String sql = "select id,student_name,head_portrait headPortrait from student where class_id =? ORDER BY CONVERT(student_name USING gbk) ASC";
        //每个班级的学生集合
        List<Map<String, Object>> stuList = studentEvaluationScoreJdbc.queryListMap(sql, classId);
        //判断显示规则的id
        if ("2".equals(id)) {
            returnMap.put("type", 2);
            //分数显示规则为总分
            sql = "select sum(fraction)  fraction  from student_evaluation_score where student_id = ?  and term_id = ?";

            for (Map<String, Object> map : stuList) {

                try {
                    map.put("list", studentEvaluationScoreJdbc.queryListMap(sql, map.get("id"), termId));
                } catch (Exception e) {
                    logger.info("没有分数");
                    map.put("list", new ArrayList<Map<String, Object>>() {
                        {
                            Map<String, Object> map2 = new HashMap<>();
                            map2.put("fractionSum", 0);
                            add(map2);
                        }
                    });
                }
            }

        } else if ("3".equals(id)) {
            returnMap.put("type", 3);
        } else {
            returnMap.put("type", 1);
            //分数显示规则为加减分分开显示
            sql = "select sum(fraction) fractionSum  from student_evaluation_score " +
                    "where student_id = ? and term_id = ? GROUP BY sign(fraction) ORDER BY fractionSum desc";
            for (Map<String, Object> map : stuList) {
                try {
                    List<Map<String, Object>> list = studentEvaluationScoreJdbc.queryListMap(sql, map.get("id"), termId);
                    if (list.isEmpty()) {
                        //应为这个学生没有分数，所以要填写默认分数
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("fractionSum", 0);
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("fractionSum", 0);
                        list.add(map1);
                        list.add(map2);
                    } else if (list.size() == 1) {
                        //判断正负数
                        if (Integer.valueOf(list.get(0).get("fractionSum").toString()) > 0) {
                            Map<String, Object> map2 = new HashMap<>();
                            map2.put("fractionSum", 0);
                            list.add(map2);
                        } else {
                            //获取负分的分数
                            Integer fractionSum = Integer.valueOf(list.get(0).get("fractionSum").toString());
                            //重新创建
                            list = new ArrayList<>();
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("fractionSum", 0);
                            Map<String, Object> map2 = new HashMap<>();
                            map2.put("fractionSum", fractionSum);
                            //赋值
                            list.add(map1);
                            list.add(map2);
                        }
                    }

                    map.put("list", list);
                } catch (Exception e) {
                    logger.info("没有分数");
                }
            }

        }
        returnMap.put("stuList", stuList);
        //默认不显示分数
        return new Result(returnMap);
    }

    @Override
    public Result findClassEvaluationScoreTwo(Integer classId, String teacherId, Integer findType, String startTime, String endTime) {
        //查询班级程序SQL
        String sql = "select id,student_name,head_portrait headPortrait from student where class_id =?";
        //每个班级的学生集合
        List<Map<String, Object>> stuList = studentEvaluationScoreJdbc.queryListMap(sql, classId);

        //分数显示规则为加减分分开显示
        sql = "select sum(fraction) fractionSum  from student_evaluation_score " +
                "where student_id = ?  ";


        //判断查询类型
        if (findType == 1) {
            logger.info("查询上周数据");
            sql += " and YEARWEEK(date_format(add_time,'%Y-%m-%d')) = YEARWEEK(now())-1 ";
        } else if (findType == 2) {
            logger.info("查询本月数据");
            sql += " and date_format(add_time,'%Y-%m')=date_format(now(),'%Y-%m') ";
        } else if (findType == 3) {
            logger.info("查询自定义数据");
            sql += " and date_format(add_time,'%Y-%m-%d')  between date_format('" + startTime + "','%Y-%m-%d') and date_format('" + endTime + "','%Y-%m-%d') ";
        } else {
            logger.info("查询本周数据");
            sql += " and YEARWEEK(date_format(add_time,'%Y-%m-%d')) = YEARWEEK(now()) ";
        }

        sql += "GROUP BY sign(fraction) ORDER BY fractionSum desc";
        for (Map<String, Object> map : stuList) {
            try {
                List<Map<String, Object>> list = studentEvaluationScoreJdbc.queryListMap(sql, map.get("id"));
                if (list.isEmpty()) {
                    //应为这个学生没有分数，所以要填写默认分数
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("fractionSum", 0);
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("fractionSum", 0);
                    list.add(map1);
                    list.add(map2);
                } else if (list.size() == 1) {
                    //判断正负数
                    if (Integer.valueOf(list.get(0).get("fractionSum").toString()) > 0) {
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("fractionSum", 0);
                        list.add(map2);
                    } else {
                        //获取负分的分数
                        Integer fractionSum = Integer.valueOf(list.get(0).get("fractionSum").toString());
                        //重新创建
                        list = new ArrayList<>();
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("fractionSum", 0);
                        Map<String, Object> map2 = new HashMap<>();
                        map2.put("fractionSum", fractionSum);
                        //赋值
                        list.add(map1);
                        list.add(map2);
                    }
                }

                map.put("list", list);
            } catch (Exception e) {
                logger.info("没有分数");
            }
        }
        return new Result(stuList);
    }

    @Override
    public Result classes(Integer scoreItemId, String name, Integer fraction, String content, String teacherId, String termId, Integer classId, Integer schoolId) {

        logger.info("评价整个班级");

        //错误信息
        List<String> errorList = new ArrayList<>();

        //查询这个班级的学生
        List<Student> stuList = studentRepository.findByClassId(classId);
        //学生评价分数记录表
        StudentEvaluationScoreRecord sesr = new StudentEvaluationScoreRecord();
        sesr.setTypeId(classId);
        sesr.setAppraiserId(Integer.valueOf(teacherId));
        sesr.setAppraiser(0);
        sesr.setContent(content);
        sesr.setFraction(fraction);
        sesr.setName(name);
        sesr.setScoreItemId(scoreItemId);
        sesr.setAddTime(new Date());
        sesr.setType(1);


        //教师评分限制
        TeacherRatingLimit trl = teacherRatingLimitRepository.findByClassIdAndTeacherId(stuList.get(0).getClassId(), Integer.valueOf(teacherId));
        //判断为空
        if (trl != null) {
            //评价分数
            Integer score = fraction < 0 ? -(fraction) : fraction;
            //判断如果小于
            if (trl.getRemainingScore() < (score * stuList.size())) {
                return new Result(CodeUtil.INSUFFICIENT_SCORE);
            }
            //修改教师本周的剩下的分数
            trl.setRemainingScore(trl.getRemainingScore() - (score * stuList.size()));
            teacherRatingLimitRepository.save(trl);
        }

        //判断评分是否为空为空就无法评分 -- 温州定制
        RatingLimitsCustomized rating = ratingLimitsCustomizedRepository.findByTeacherId(Integer.valueOf(teacherId));
        //判断评分是否为空为空就无法评分 -- 温州定制
        if (rating != null) {
//            //评价分数
//            Integer score = rating.getSurplus()<0 ? -(rating.getSurplus()) : rating.getSurplus();
            Integer score = fraction < 0 ? -(fraction) : fraction;
            //判断如果小于
            if (rating.getFraction() < (score * stuList.size())) {
                return new Result(CodeUtil.INSUFFICIENT_SCORE);
            }
            studentEvaluationScoreJdbc.updateByParameter("update rating_limits_customized set fraction=? where teacher_id=?", rating.getFraction() - score * stuList.size(), sesr.getAppraiserId());
        }

        if (trl == null && rating == null) {
            return new Result(CodeUtil.INSUFFICIENT_SCORE);
        }

        //学生评价分数记录id
        Integer scoreRecordId = studentEvaluationScoreRecordRepository.save(sesr).getId();


        for (Student stu : stuList) {
            try {
                //创建一个学生评分对象
                StudentEvaluationScore ses = new StudentEvaluationScore();
                ses.setStudentId(stu.getId());
                ses.setAppraiserId(Integer.valueOf(teacherId));
                ses.setContent(content);
                ses.setFraction(fraction);
                ses.setName(name);
                ses.setScoreItemId(scoreItemId);
                ses.setTermId(Integer.valueOf(termId));
                ses.setType(1);
                ses.setScoreRecordId(scoreRecordId);
                ses.setSchoolId(schoolId);
                //给单个学生评分
                personal(ses);
            } catch (Exception e) {
                logger.info(stu.getStudentName() + "同学评分失败");
                errorList.add(stu.getStudentName() + "同学评分失败");
            }
        }

        //判断是否有错误信息
        if (errorList.size() == 0) {
            return new Result(errorList);
        }
        return new Result();
    }


    public Integer personal(StudentEvaluationScore ses) {


        if (ses.getType() == 0) {
            //学生评价分数记录表
            StudentEvaluationScoreRecord sesr = new StudentEvaluationScoreRecord();
            sesr.setTypeId(ses.getStudentId());
            sesr.setAppraiserId(ses.getAppraiserId());
            sesr.setAppraiser(0);
            sesr.setContent(ses.getContent());
            sesr.setFraction(ses.getFraction());
            sesr.setName(ses.getName());
            sesr.setScoreItemId(ses.getScoreItemId());
            sesr.setAddTime(new Date());
            sesr.setType(0);

            //查询学生的班级
            String sql = "select class_id string from student where id = ?";
            String classId = studentEvaluationScoreJdbc.queryString(sql, ses.getStudentId());
            //教师评分限制
            TeacherRatingLimit trl = teacherRatingLimitRepository.findByClassIdAndTeacherId(Integer.valueOf(classId), ses.getAppraiserId());
//            Integer integer = studentEvaluationScoreJdbc.queryInteger("SELECT rlc.fraction ints FROM rating_limits_customized rlc  WHERE  rlc.teacher_id=?", sesr.getAppraiserId());


            //判断为空
            if (trl != null) {
                //评价分数
                Integer score = ses.getFraction() < 0 ? -(ses.getFraction()) : ses.getFraction();
                //判断如果小于
                if (trl.getRemainingScore() < score) {
                    return 2;
                }
                trl.setRemainingScore(trl.getRemainingScore() - score);
                teacherRatingLimitRepository.save(trl);

            }
            //判断评分是否为空为空就无法评分 -- 温州定制
            RatingLimitsCustomized rating = ratingLimitsCustomizedRepository.findByTeacherId(Integer.valueOf(ses.getAppraiserId()));
            //判断评分是否为空为空就无法评分 -- 温州定制
            if (rating != null) {

                //评价分数
                Integer score = ses.getFraction() < 0 ? -(ses.getFraction()) : ses.getFraction();
                //判断如果小于
                if (rating.getFraction() < score) {
                    return 2;
                }
                studentEvaluationScoreJdbc.updateByParameter("update rating_limits_customized set fraction=? where teacher_id=?", rating.getFraction() - score, sesr.getAppraiserId());
            }

            if (trl == null && rating == null) {
                return 2;
            }


            //学生评价分数记录id
            Integer scoreRecordId = studentEvaluationScoreRecordRepository.save(sesr).getId();
            ses.setScoreRecordId(scoreRecordId);
        }

        ses.setAppraiser(0);
        ses.setAddTime(new Date());

        try {
            studentEvaluationScoreRepository.save(ses);
            //查询兑换详情表
            StudentExchangeDetails sed = studentExchangeDetailsRepository.findByStudentId(ses.getStudentId());
            //如果为空
            if (sed == null) {
                sed = new StudentExchangeDetails();
                logger.info("学生兑换详情为空，添加");
                sed.setFraction(ses.getFraction());
                sed.setPrizeNumber(0);
                sed.setRedeemedPoints(0);
                sed.setSchoolId(ses.getSchoolId());
                sed.setStudentId(ses.getStudentId());
            } else {
                logger.info("学生兑换详情不为空，修改");
                sed.setFraction(sed.getFraction() + ses.getFraction());
            }
            studentExchangeDetailsRepository.save(sed);
        } catch (Exception e) {
            logger.error("错误原因:{}", e);
        }

        //小程序推送 scorePush(ses);
        //公众号号推送
        try {
            officialAccountPush(ses);
        } catch (Exception e) {
            logger.error("e", e);
        }
        return 1;
    }

    @Override
    public Result group(Integer scoreItemId, String name, Integer fraction, String content, String teacherId, String termId, Integer groupId, Integer schoolId) {

        logger.info("评价整个组");

        //错误信息
        List<String> errorList = new ArrayList<>();

        //查询这个组的学生
        List<Student> stuList = studentRepository.findByGroupId(groupId);

        //学生评价分数记录表
        StudentEvaluationScoreRecord sesr = new StudentEvaluationScoreRecord();
        sesr.setTypeId(groupId);
        sesr.setAppraiserId(Integer.valueOf(teacherId));
        sesr.setAppraiser(0);
        sesr.setContent(content);
        sesr.setFraction(fraction);
        sesr.setName(name);
        sesr.setScoreItemId(scoreItemId);
        sesr.setAddTime(new Date());
        sesr.setType(2);

        //评分限制
        //教师评分限制
        TeacherRatingLimit trl = teacherRatingLimitRepository.findByClassIdAndTeacherId(stuList.get(0).getClassId(), Integer.valueOf(teacherId));
        //判断为空
        if (trl != null) {
            //评价分数
            Integer score = fraction < 0 ? -(fraction) : fraction;
            //判断如果小于
            if (trl.getRemainingScore() < (score * stuList.size())) {
                return new Result(CodeUtil.INSUFFICIENT_SCORE);
            }
            //修改教师本周的剩下的分数
            trl.setRemainingScore(trl.getRemainingScore() + (score * stuList.size()));
            teacherRatingLimitRepository.save(trl);
        }
        //判断评分是否为空为空就无法评分 -- 温州定制
        RatingLimitsCustomized rating = ratingLimitsCustomizedRepository.findByTeacherId(Integer.valueOf(teacherId));
        //判断评分是否为空为空就无法评分 -- 温州定制
        if (rating != null) {
            Integer score = fraction < 0 ? -(fraction) : fraction;
            //判断如果小于
            if (rating.getFraction() < (score * stuList.size())) {
                return new Result(CodeUtil.INSUFFICIENT_SCORE);
            }
            studentEvaluationScoreJdbc.updateByParameter("update rating_limits_customized set fraction=? where teacher_id=?", rating.getFraction() - score * stuList.size(), sesr.getAppraiserId());

        }


        if (trl == null && rating == null) {
            return new Result(CodeUtil.INSUFFICIENT_SCORE);
        }


        //学生评价分数记录id
        Integer scoreRecordId = studentEvaluationScoreRecordRepository.save(sesr).getId();

        for (Student stu : stuList) {
            try {

                //创建一个学生评分对象
                StudentEvaluationScore ses = new StudentEvaluationScore();
                ses.setStudentId(stu.getId());
                ses.setAppraiserId(Integer.valueOf(teacherId));
                ses.setContent(content);
                ses.setFraction(fraction);
                ses.setName(name);
                ses.setScoreItemId(scoreItemId);
                ses.setTermId(Integer.valueOf(termId));
                ses.setType(2);
                ses.setScoreRecordId(scoreRecordId);
                ses.setSchoolId(schoolId);
                //给单个学生评分
                personal(ses);
            } catch (Exception e) {
                logger.info(stu.getStudentName() + "同学评分失败");
                errorList.add(stu.getStudentName() + "同学评分失败");
            }
        }

        //判断是否有错误信息
        if (errorList.size() == 0) {
            return new Result(errorList);
        }
        return new Result();

    }


    /**
     * 评分推送
     *
     * @param ses 评分信息
     * @return
     */
    public int scorePush(StudentEvaluationScore ses) {

        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";
        //家长openid
        Map<String, Object> parent = studentEvaluationScoreJdbc.queryMap(sql, ses.getStudentId());
        //家长的openId
        String openId = (String) parent.get("open_id_one");

        sql = "select COUNT(1) count from user_subscription_template ust left JOIN we_chat_template wt " +
                "on(wt.id=ust.template_id) where wt.template_id='P8-fnILrRjQhjTANQMyrxfdMnc-Rt8ymBlga-wW6Xw8' and ust.open_id =? and ust.state=0 ";
        //判断这个用户这个小程序是否订阅了
        int count = studentEvaluationScoreJdbc.queryCount(sql, openId);
        //判断openId是否为空
        if (!StringUtils.isEmpty(openId) && count > 0) {

            String accessToken = wXJdbc.getAccessToken(1);
            //查询学生名字
            sql = "select student_name string from student where id = ?";
            String studenName = studentEvaluationScoreJdbc.queryString(sql, ses.getStudentId());
            sql = "select name string from teacher where id = ?";
            String teacherName = studentEvaluationScoreJdbc.queryString(sql, ses.getAppraiserId());
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("name1", studenName);
            pushMap.put("name8", teacherName);
            pushMap.put("time4", DateUtil.time());
            pushMap.put("thing3", ses.getName());
            pushMap.put("thing9", StringUtils.isEmpty(ses.getContent()) ? "无" : ses.getContent());

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送订阅消息
            WXUtil.sendWechatmsgToUser(accessToken, openId, "P8-fnILrRjQhjTANQMyrxfdMnc-Rt8ymBlga-wW6Xw8", "", json, "", "");
            studentEvaluationScoreJdbc.updateSubscribe(openId, "P8-fnILrRjQhjTANQMyrxfdMnc-Rt8ymBlga-wW6Xw8");
        }
        return 1;
    }

    /**
     * 公众号推送
     *
     * @param ses
     */
    public void officialAccountPush(StudentEvaluationScore ses) {

        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";
        //家长openid
        Map<String, Object> parent = studentEvaluationScoreJdbc.queryMap(sql, ses.getStudentId());
        //家长的openId
        String openId = (String) parent.get("open_id_two");

        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
        //判断openId是否为空
        if (!StringUtils.isEmpty(openId)) {


            //查询学生名字
            sql = "select student_name string from student where id = ?";
            String studenName = studentEvaluationScoreJdbc.queryString(sql, ses.getStudentId());
            sql = "select name string from teacher where id = ?";
            String teacherName = studentEvaluationScoreJdbc.queryString(sql, ses.getAppraiserId());

            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first", "家长您好，您的孩子有一条新的评价信息。");
            pushMap.put("keyword1", studenName);
            pushMap.put("keyword2", teacherName);
            pushMap.put("keyword3", ses.getName());
            pushMap.put("keyword4", "" + ses.getFraction() + "分");
            pushMap.put("keyword5", DateUtil.time());
            pushMap.put("remark", "感谢您的支持。");

            //跳转小程序信息
            JSONObject appletJson = new JSONObject();
            appletJson.put("appid", "wx30b606bac7775eba");
            appletJson.put("pagepath", "pages/evaluate/index");

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken, openId, "aPysfnjC1jCISCqp8RstlJwxZkKd93jXkrollyWrrlg", "", appletJson, json);
        }
    }
}
